const path = require('path')
const fs = require('fs')

const { uniConfigLog } = require('./log')
const { get, set } = require('lodash')

const log = uniConfigLog

const utils = {
    get,
    set,
    getDate() {
        const date = new Date()
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()
        const hour = date.getHours()
        const minute = date.getMinutes()
        const second = date.getSeconds()
        return year + '年' + month + '月' + day + '日 ' + hour + ':' + minute + ':' + second
    },

    async hasFile(file, cwd = global.PRESET_PATH) {
        return new Promise((resolve) => {
            fs.access(path.join(cwd, file), fs.constants.F_OK, (err) => {
                resolve(!!!err)
            })
        })
    },

    async getFileData(file, cwd = global.PRESET_PATH) {
        return new Promise(async (resolve, reject) => {
            try {
                const data = fs.readFileSync(path.join(cwd, file), 'utf8')
                resolve(data)
            } catch (e) {
                // TODO 出错了
                log('未找到此文件：' + file, 'error')
                resolve(false)
            }
        })
    },

    async writeFileData(file, data, cwd = global.PRESET_PATH) {
        return new Promise(async (resolve) => {
            try {
                fs.writeFileSync(path.join(cwd, file), data)
                resolve(true)
            } catch (e) {
                // TODO 出错了
                log('读取文件出错：' + file)
                resolve(false)
            }
        })
    },

    mkDirsSync (dirname) {
        if (fs.existsSync(dirname)) {
            return true;
        } else {
            if (utils.mkDirsSync(path.dirname(dirname))) {
                fs.mkdirSync(dirname);
                return true;
            }
        }
    }
}

module.exports = utils
